package com.yx.learn.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.yx.learn.dao.CompanyDao;
import com.yx.learn.domain.Company;

@Repository("companyDao")
public class CompanyDaoImpl implements CompanyDao {

	@Autowired
	@Qualifier("hibernateTemplate")
	private HibernateTemplate hibernateTemplate;

	public void saveCompany(Company company) throws Exception {
		// TODO Auto-generated method stub

		hibernateTemplate.save(company);
	}

	public void deleteCompany(Company company) throws Exception {
		// TODO Auto-generated method stub

		hibernateTemplate.delete(company);
	}

	public void updateCompany(Company company) throws Exception {
		// TODO Auto-generated method stub

		hibernateTemplate.merge(company);
	}

	@SuppressWarnings("unchecked")
	public Company findById(int id) throws Exception {
		// TODO Auto-generated method stub

		String hql = "From Company where id=?";
		List<Company> companies = hibernateTemplate.find(hql, id);
		return companies.isEmpty() ? null : companies.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<Company> findAllCompanies() throws Exception {
		// TODO Auto-generated method stub
		String hql = "From Company";
		List<Company> companies = hibernateTemplate.find(hql);
		return companies;
	}

	@SuppressWarnings("unchecked")
	public List<Company> findCompanies(String hql) throws Exception {
		// TODO Auto-generated method stub
		return hibernateTemplate.find(hql);
	}

	@SuppressWarnings("unchecked")
	public List<Company> findCompanies(String hql, int pageNumber, int pageSize)
			throws Exception {
		Query query = hibernateTemplate.getSessionFactory().getCurrentSession()
				.createQuery(hql);
		query.setFirstResult((pageNumber - 1) * pageSize);
		query.setMaxResults(pageSize);
		List<Company> companies = query.list();
		return companies;
	}

}
